/*
 * @Author: gyc
 * @Date: 2020-06-11 08:22:43
 * @LastEditTime: 2020-06-11 14:04:04
 * @Description: Nuxt测试版
 */
const AES = require("./config/utils")
const LocalStrategy = require('passport-local').Strategy;
module.exports = app => {
    // 自定义内容
    app.projectName = 'egg'

    app.beforeStart(async () => {
        // 应用会等待这个函数执行完成才启动
        console.log("==app beforeStart==");
    });

    app.ready(async () => {
        console.log("==app ready==");
    })

    app.beforeClose(async () => {
        console.log("==app beforeClose==");
    })

    // 挂载 strategy
    app.passport.use(new LocalStrategy({
        passReqToCallback: true,
    }, (req, username, password, done) => {
        // format user
        const user = {
            provider: 'local',
            username,
            password,
        };
        app.passport.doVerify(req, user, done);
    }));

    app.passport.verify(async (ctx, user) => {
        // 查找数据库，并验证密码是否正确
        let foundUser = await ctx.service.user.findOne(user.username, user.password)
        if (foundUser && foundUser.password === AES.Encrypt(user.password)) {
            console.log('ok!')
            return foundUser
        } else {
            return false
        }
    });

    // 序列化与反序列化，序列化存储到session中只保存用户id
    app.passport.serializeUser(async (ctx, user) => {
        // return pick(user, ['id', 'name', 'username', 'email']);
        return user;
    });

    app.passport.deserializeUser(async (ctx, user) => {
        return user;
    });
};